package com.ruoyi.generator.controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.generator.domain.GenTable;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.generator.domain.WBackupRecord;
import com.ruoyi.generator.service.IWBackupRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 数据备份记录Controller
 * 
 * @author lynn
 * @date 2023-08-01
 */
@Slf4j
@Api(tags = "数据备份记录管理")
@RestController
@RequestMapping("/tool/backupRecord")
public class WBackupRecordController extends BaseController
{
    @Autowired
    private IWBackupRecordService wBackupRecordService;

    /**
     * 查询数据备份记录列表
     */
    @ApiOperation("获取数据备份记录列表")
    @PreAuthorize("@ss.hasPermi('system:backups:list')")
    @GetMapping("/list")
    public TableDataInfo list(WBackupRecord wBackupRecord)
    {
        startPage();
        List<WBackupRecord> list = wBackupRecordService.list(wBackupRecord.queryWrapper());
        return getDataTable(list);
    }

    /**
     * 导出数据备份记录列表
     */
    @ApiOperation("导出数据备份记录列表")
    @PreAuthorize("@ss.hasPermi('system:backups:exprot')")
    @Log(title = "数据备份记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WBackupRecord wBackupRecord)
    {
        List<WBackupRecord> list = wBackupRecordService.list(wBackupRecord.queryWrapper());
        ExcelUtil<WBackupRecord> util = new ExcelUtil<WBackupRecord>(WBackupRecord.class);
        util.exportExcel(response, list, "数据备份记录数据");
    }

    /**
     * 导入数据备份记录列表
     */
    @ApiOperation("导入数据备份记录列表")
    @PreAuthorize("@ss.hasPermi('tool:backupRecord:import')")
    @Log(title = "数据备份记录", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<WBackupRecord> util = new ExcelUtil<WBackupRecord>(WBackupRecord.class);
        List<WBackupRecord> list = util.importExcel(file.getInputStream());
        return success(wBackupRecordService.saveBatch(list));
    }

    /**
     * 获取数据备份记录详细信息
     */
    @ApiOperation("获取数据备份记录详细")
    @ApiImplicitParam(name = "id", value = "数据备份记录ID", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('tool:backupRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(wBackupRecordService.getById(id));
    }

    /**
     * 新增数据备份记录
     */
    @ApiOperation("新增数据备份记录")
    @PreAuthorize("@ss.hasPermi('tool:backupRecord:add')")
    @Log(title = "数据备份记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WBackupRecord wBackupRecord)
    {
        return toAjax(wBackupRecordService.saveBackupRecord(wBackupRecord));
    }

    /**
     * 数据恢复
     */
    @ApiOperation("上传sql文件恢复数据")
    @PreAuthorize("@ss.hasPermi('tool:backupRecord:recover')")
    @Log(title = "上传sql文件恢复数据", businessType = BusinessType.IMPORT)
    @PostMapping("/uploadFileRecover")
    public AjaxResult uploadFileRecover(MultipartFile file)
    {
        try {
            boolean b = wBackupRecordService.uploadFileRecover(file);
            return toAjax(b);
        }catch (IOException e){
            return toAjax(false);
        }
    }
    /**
     * 数据恢复
     */
    @ApiOperation("本地sql文件恢复数据")
    @PreAuthorize("@ss.hasPermi('tool:backupRecord:recover')")
    @Log(title = "本地sql文件恢复数据", businessType = BusinessType.IMPORT)
    @PostMapping("/localFileRecover")
    public AjaxResult localFileRecover(@RequestBody WBackupRecord wBackupRecord)
    {
        try {
            boolean b = wBackupRecordService.localFileRecover(wBackupRecord);
            return toAjax(b);
        }catch (IOException e){
            return toAjax(false);
        }
    }

    /**
     * 修改数据备份记录
     */
    @ApiOperation("更新数据备份记录")
    @PreAuthorize("@ss.hasPermi('system:backups:edit')")
    @Log(title = "数据备份记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WBackupRecord wBackupRecord)
    {
        // 只能修改备注
        WBackupRecord wBackupRecordTemp = new WBackupRecord();
        wBackupRecordTemp.setId(wBackupRecord.getId());
        wBackupRecordTemp.setRemark(wBackupRecord.getRemark());
        return toAjax(wBackupRecordService.updateById(wBackupRecordTemp));
    }

    /**
     * 删除数据备份记录
     */
    @ApiOperation("删除数据备份记录")
    @ApiImplicitParam(name = "ids", value = "数据备份记录ID集合", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('system:backups:remove')")
    @Log(title = "数据备份记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids)
    {
        return toAjax(wBackupRecordService.removeByIds(ids));
    }


    /**
     * sql文件下载
     */
    @ApiOperation("sql文件下载")
    @GetMapping("/download/resource")
    public void resourceDownload(String id, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        WBackupRecord backupRecord = wBackupRecordService.getById(id);
        String resource = backupRecord.getFilePath();
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }

            // 下载名称
            String downloadName = StringUtils.substringAfterLast(resource, "\\");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(resource, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}
